//
//  SEGNewFeedebackViewController.m
//  ExcellentHome
//
//  Created by liangxinqiang on 15-4-24.
//  Copyright (c) 2015年 陈区. All rights reserved.
//

#import "SEGNewFeedebackViewController.h"
#import "SEGNewFeedebackViewModel.h"

#if __has_include(<WechatOpenSDK/WXApi.h>)
#import <WechatOpenSDK/WXApi.h>
#else
#import "WXApi.h"
#endif

@interface SEGNewFeedebackViewController ()
@property (nonatomic, strong)UIScrollView *backView;

@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong)UITextView *contentInputView;
@property(nonatomic, strong) SEGNewFeedebackViewModel *viewModel;
@end

@implementation SEGNewFeedebackViewController{
    UIView *placeholderLabel;
}
@synthesize context = _context;

-(void)layoutViews{
    [self.view addSubview:self.backView];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.contentInputView];
    
    [self.backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.mas_equalTo(63);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(1);
        make.top.equalTo(self.backView.mas_bottom);
    }];

    [self.contentInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(140);
        make.top.equalTo(self.lineView.mas_bottom);
    }];
    
    for (UIView *object in self.contentInputView.subviews) {
        if (object.tag == 1001 && [object isKindOfClass:[UILabel class]]) {
            placeholderLabel = object;
            [object mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(object.superview);
                make.top.equalTo(object.superview).offset(5);
            }];
        }
    }
    [self updateUI];
}

-(void)updateUI{
    [self.backView removeAllSubviews];
    __block CGFloat x = 15;
    [self.viewModel.dataSource enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull object, NSUInteger idx, BOOL * _Nonnull stop) {
        Boolean hasSelected = [[object valueForKey:@"hasSelected"] boolValue];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor: hasSelected ? kColor_T : kColor_1 forState:UIControlStateNormal];
        [button setTitle: [object valueForKey:@"title"] forState:UIControlStateNormal];
        [button setBackgroundColor:hasSelected ? [UIColor colorWithRed:242.F/255.F green:248.F/255.F blue:229.F/255.F alpha:1] : kColor_W ];
        button.layer.cornerRadius = 2.0;
        button.layer.masksToBounds = YES;
        button.layer.borderWidth = 0.5;
        button.layer.borderColor = hasSelected ? kColor_T.CGColor : kColor_L2.CGColor;
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.backView addSubview:button];
        button.frame = CGRectMake(x, 17, 100, 30);
        x += 100 + 10;
        button.tag = idx;
    }];
    self.backView.contentSize = CGSizeMake(30 + self.viewModel.dataSource.count *100 + (self.viewModel.dataSource.count -1) * 10, CGRectGetHeight(self.backView.frame));
}

-(void)buttonClick:(UIButton*)sender{
    [self.viewModel changeSelectedSource:sender.tag];
    [self updateUI];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"产品反馈";
    [self showCustomNavigationBackButton];
    [self showCustomNavigationRightButtonWithTitle:@"提交" image:[UIImage imageWithContentsOfFile:SEGPicName(@"")] hightlightImage:[UIImage imageWithContentsOfFile:SEGPicName(@"")] color:kColor_T];
    
    [self layoutViews];
}

#pragma mark - 新网络请求
- (void)requestSubmitAdviceWithContext:(NSString*)context SugType:(NSString*)type
{
    [SVProgressHUD show];
    [self.viewModel requestSuggestsaveWithContext:context SugType:type completed:^(NSString * _Nonnull codeType, NSString * _Nonnull errorMessage)  {
        [SVProgressHUD dismiss];
        if ([codeType isEqualToString:@"0"]) {
            self->contextTextView.text = @"请填写您的建议或反馈,我们会及时改进";
            self->contextTextView.textColor = kColor_3;
            self.context = nil;
            UIAlertView* alertview = [[UIAlertView alloc] initWithTitle:nil
                                                                message:@"提交成功!"
                                                               delegate:self
                                                      cancelButtonTitle:nil
                                                      otherButtonTitles:@"确认", nil];
            [alertview show];
            alertview.tag = 1;
        }
        else {
            UIAlertView* alertview = [[UIAlertView alloc] initWithTitle:nil
                                                                message:errorMessage
                                                               delegate:nil
                                                      cancelButtonTitle:@"确认"
                                                      otherButtonTitles:nil];
            [alertview show];
        }
    }];
}

//右侧按钮
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    
    if ([self.contentInputView.text length] <= 0) {
        [SEGAlertView showTmepMessageWithMessage:@"请填写您的建议或反馈！"];
        return;
    }
    
    //    [self.view endEditing:YES];
    NSString *sugType = @"";
    for (NSDictionary *object in self.viewModel.dataSource) {
        if ([[object valueForKey:@"hasSelected"] boolValue]) {
            sugType = [object valueForKey:@"type"];
            break;
        }
    }
    [self requestSubmitAdviceWithContext:self.contentInputView.text SugType:sugType];
    
    
    //[contextTextView resignFirstResponder];
    [mainView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)textViewDidBeginEditing:(UITextView*)textView{
}

- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if (placeholderLabel) {
        [placeholderLabel setHidden:([[textView.text stringByReplacingCharactersInRange:range withString:text] length] > 0)? YES:NO];
    }
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        [mainView setContentOffset:CGPointMake(0, 0) animated:YES];
        return NO;
    }
    if (range.length == 1 && [text isEqualToString:@""]) { //退格键
        return YES;
    }
    if ([[textView.text stringByReplacingCharactersInRange:range withString:text] length] > 500) return NO;
    return YES;
}

- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    if (alertView.tag == 1) {
        if (buttonIndex == 0) {
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
        }
    }
   else if (alertView.tag == 1003) {
        if (buttonIndex == 1) {
            UIViewController *VC = [[SEGUhomeMediator sharedInstance] seg_initSubmitUserAtuhViewController:nil];
            [self.navigationController pushViewController:VC animated:YES];
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITraitEnvironment
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    // 更新layer
    [self.viewModel.dataSource enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull object, NSUInteger idx, BOOL * _Nonnull stop) {
        Boolean hasSelected = [[object valueForKey:@"hasSelected"] boolValue];
        UIButton *button = (UIButton *)[_backView viewWithTag:idx];
        button.layer.borderColor = hasSelected ? kColor_T.CGColor : kColor_L2.CGColor;
    }];
}

-(UIScrollView *)backView{
    if (!_backView) {
        _backView = [[UIScrollView alloc]init];
        _backView.backgroundColor = kColor_W;
        _backView.contentSize = CGSizeMake(0, 0);
        _backView.showsVerticalScrollIndicator = NO;
        _backView.showsHorizontalScrollIndicator = NO;
    }
    return _backView;
}

-(UIView *)lineView{
    if (!_lineView){
        _lineView = [[UIView alloc]init];
        _lineView.backgroundColor = kColor_L2;
        //_lineView.layer.cornerRadius = 2;
    }
    return _lineView;
}

-(UITextView *)contentInputView{
    if (!_contentInputView){
        _contentInputView = [[UITextView alloc] init];
        _contentInputView.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
        _contentInputView.textColor = kColor_1;
        _contentInputView.delegate = self;
        _contentInputView.backgroundColor = kColor_W;
        _contentInputView.returnKeyType = UIReturnKeyDone;
        _contentInputView.keyboardType = UIKeyboardTypeDefault;
        
        UILabel *placeholderLabel = [[UILabel alloc]init];
        [_contentInputView addSubview:placeholderLabel];
        [placeholderLabel setText:@"请填写您的建议或反馈,我们会及时改进"];
        placeholderLabel.tag = 1001;
        placeholderLabel.textColor = kColor_C;
        placeholderLabel.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
        [placeholderLabel sizeToFit];
    }
    return _contentInputView;
}

#pragma mark - init Views
-(void)segInitViews{

}

#pragma mark - RAC Data Binding
- (void)bindViewModel {
}

#pragma mark - getter
-(SEGNewFeedebackViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[SEGNewFeedebackViewModel alloc]init];
    }
    return _viewModel;
}
@end
